$(document).ready(function () {
  var validateUsername = $('#validateUsername');
  var Username = $('#username');
  var objCountdown;
  var timer= new Array();
  $('#username').bind('keyup focus blur change',function () {
    this.value = this.value.replace(/[^0-9A-Za-z.\-_]+/gim,"");
    var t = this; 
    if (this.value != this.lastValue) {
      if (timer[1]) clearTimeout(timer[1]);
      if (timer[2]) clearTimeout(timer[2]);
      validateUsername.removeClass('error').html('<img src="/themes/gfx/ajax-loader.gif" height="16" width="16" hspace="10" align="left" /> checking availability...').parent().removeClass().addClass('allok validate');
      
      timer[1] = setTimeout(function () {
        $.ajax({
          url: '/ajax/register/CheckUsername/' + escape(t.value),
          dataType: 'json',
          type: 'get',
          success: function (j) {
            validateUsername.html(j.msg);
            Username.removeClass().addClass('input_error');
            validateUsername.parent().removeClass().addClass(j.cssclass + ' validate');
            //validateUsername.remove('.countdown');
            //validateUsername.append('<span class="countdown"></span>');
            if(objCountdown){
                    window.clearInterval(objCountdown._interval);
                }
            if (j.cssclass == 'allok') {
                Username.removeClass().addClass('input_ok');
                objCountdown = $("#infoUsername span.countdown").counter({sec:"10",message_befor: 'This info will close after ', message_after: ' seconds.', finish_function:'after_countdown()'});
            } else {
                $("#infoUsername span.countdown").html("");
            }
          }
        });
      }, 200);
      
      this.lastValue = this.value;
    }
  });

});
function after_countdown () {
    var validateUsername = $('#validateUsername');
    var Username = $('#username');
    
    validateUsername.html('');
    Username.removeClass().addClass('input_ok');
    validateUsername.parent().removeClass(); 
}
